package com.der.play.listeners;

import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.boot.context.event.ApplicationContextInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author K0790016
 **/
@Slf4j
public class ConstantsListener implements ApplicationListener<ApplicationContextInitializedEvent>, Ordered {
    @Override
    public void onApplicationEvent(ApplicationContextInitializedEvent applicationContextInitializedEvent) {
        ConfigurableEnvironment environment = applicationContextInitializedEvent.getApplicationContext().getEnvironment();
        String url = environment.getProperty("spring.datasource.url");
        String username = environment.getProperty("spring.datasource.username");
        String password = environment.getProperty("spring.datasource.password");
        if (StringUtils.isAnyBlank(url, username, password)) {
            log.error("获取数据库数据异常：{}，{}，{}", url, username, password);
        }
        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, username, password);
            Entity query = SqlExecutor.query(connection, "SELECT name, password FROM der_user_table where id = ? ", new EntityHandler(), 4);
            log.info("结果：{}", JSONUtil.toJsonPrettyStr(query));
        } catch (SQLException e) {
            log.error("获取数据库数据异常：{}，{}，{}，e：{}", url, username, password, ExceptionUtils.getStackTrace(e));
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    log.error("获取数据库数据断开异常：{}，{}，{}，e：{}", url, username, password, ExceptionUtils.getStackTrace(e));
                }
            }
        }

    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
